package com.example.dingtalklogin.manager.dingtalk;

import com.example.dingtalklogin.common.util.SpringUtil;
import com.example.dingtalklogin.event.DingtalkTokenRefreshEvent;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 钉钉老接口oapi的token无效拦截器，尝试发布token刷新事件，刷新token，并重新调用
 * @author xuzhen97
 */
@Component
@Slf4j
@Aspect
public class OApiTokenInvalidAop {

    @Pointcut("execution(* com.example.dingtalklogin.manager.dingtalk.DingtalkOApiClient.*(..))")
    public void pointCut() { }

    @Around("pointCut()")
    public Object doApiLogAround(ProceedingJoinPoint joinPoint) throws Throwable {

        OApiResponse response = (OApiResponse) joinPoint.proceed();

        if(response.getErrCode() != 0){
            // 发布token刷新事件, 并重新调用方法
            DingtalkTokenRefreshEvent event = new DingtalkTokenRefreshEvent(this, response.getErrMsg());
            SpringUtil.getEventPublisher().publishEvent(event);
            return joinPoint.proceed();
        }

        return response;
    }

}
